package cn.cnf.service.impl;

import cn.cnf.common.enums.RecommendState;
import cn.cnf.common.enums.StateEnum;
import cn.cnf.common.enums.VerifyState;
import cn.cnf.common.exception.CustomException;
import cn.cnf.common.utils.BigDecimalUtil;
import cn.cnf.common.utils.UserRequestUtil;
import cn.cnf.entity.Chapter;
import cn.cnf.entity.Novel;
import cn.cnf.entity.NovelDetails;
import cn.cnf.entity.User;
import cn.cnf.entity.vo.NovelDetailsInfo;
import cn.cnf.mapper.NovelMapper;
import cn.cnf.service.ChapterService;
import cn.cnf.service.NovelDetailsService;
import cn.cnf.service.NovelService;
import cn.cnf.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author ZhuMeiYi
 * @date 2020/12/4 18:13
 * @description
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
@Service
@Transactional(rollbackFor = {RuntimeException.class, Error.class})
public class NovelServiceImpl extends ServiceImpl<NovelMapper, Novel> implements NovelService {

    private final NovelMapper novelMapper;

    @Autowired
    private UserService userService;
    @Autowired
    private NovelDetailsService novelDetailsService;
    @Autowired
    private NovelService novelService;
    @Autowired
    private ChapterService chapterService;


    @Override
    public String addOrUpdate(Novel novel) {

        if (StringUtils.isBlank(novel.getId())){
            User user = userService.findUserByUsername(UserRequestUtil.getCurrentUserName());
            novel.setAuthorId(user.getId());
            novel.setRecommend(0);
            novel.setVerifyState(0);
            novel.setCommentNum(0);
            novel.setCollectNum(0);
            novel.setSubscribeNum(0);
        }

        novel.setVerifyState(VerifyState.VERIFYING.getValue());
        saveOrUpdate(novel);
        return novel.getId();
    }

    @Override
    public boolean isAuthor(String novelId, String userId) {
        List<Novel> list = list(new LambdaQueryWrapper<Novel>().eq(Novel::getId, novelId).eq(Novel::getAuthorId, userId));
        return !CollectionUtils.isEmpty(list);
    }

    @Override
    public String addOrNovelDetails(NovelDetails novelDetails) {
//        LambdaQueryWrapper<NovelDetails> wrapper = new LambdaQueryWrapper<NovelDetails>()
//                .eq(NovelDetails::getNovelId, novelDetails.getNovelId())
//                .eq(NovelDetails::getNovelChapterId, novelDetails.getNovelChapterId());
//        if (!CollectionUtils.isEmpty(novelDetailsService.list(wrapper))){
//            throw new CustomException("此章节小说已存在");
//        }
        novelDetails.setId(novelDetails.getDetailsId());
        novelDetailsService.saveOrUpdate(novelDetails);
        return novelDetails.getId();
    }

    @Override
    public IPage<Novel> selectPage(Integer current, Integer pageSize,String name) {
        LambdaQueryWrapper<Novel> wrapper = new LambdaQueryWrapper<Novel>()
                .eq(Novel::getVerifyState, VerifyState.VERIFIED.getValue())
                .like(name!=null,Novel::getNovelName,name);
        return novelMapper.selectPage(new Page<>(current, pageSize), wrapper);
    }

    @Override
    public NovelDetailsInfo getChapterDetails(String novelId, String chapterId) {
        if(StringUtils.isBlank(novelId)||StringUtils.isBlank(chapterId)){
            throw new CustomException("请传入完整信息");
        }
        NovelDetails novelDetails = novelDetailsService.getNovelDetails(novelId, chapterId);
        if (novelDetails==null||StringUtils.isBlank(novelDetails.getContent())){
            throw new CustomException("没有找到小说详细");
        }
        Novel novel = novelService.getById(novelId);
        Chapter chapter = chapterService.getById(chapterId);
        NovelDetailsInfo novelDetailsInfo = new NovelDetailsInfo();
        novelDetailsInfo.setNovelId(novelId);
        novelDetailsInfo.setNovelChapterId(chapterId);
        novelDetailsInfo.setNovelName(novel.getNovelName());
        novelDetailsInfo.setChapterName(chapter.getChapterName());
        novelDetailsInfo.setContent(novelDetails.getContent());
        novelDetailsInfo.setNeedMoney(chapter.getNeedMoney());
        novelDetailsInfo.setId(novelDetails.getId());
        return novelDetailsInfo;
    }

    @Override
    public BigDecimal adjustNovelMoneyById(String novelId, BigDecimal num) {
        Novel novel = getById(novelId);
        BigDecimal result = BigDecimalUtil.safeAdd(novel.getIncome(), num);
        if (BigDecimalUtil.lessThan(result,BigDecimal.ZERO)) {
            throw new CustomException("余额不足");
        } else {
            if (novelMapper.updateIncome(novelId,result)<=0){
                throw new CustomException("金额调整失败");
            }
            return result;
        }
    }

    @Override
    public String recommend(String novelId, RecommendState state) {
        Novel novel = new Novel();
        novel.setId(novelId);
        novel.setRecommend(state.getValue());
        if (novelMapper.updateRecommend(novelId,state.getValue())<=0) {
            throw new CustomException("推荐状态修改失败");
        }
        return novelId;
    }

    @Override
    public IPage<Novel> getVerifying(Integer current, Integer pageSize) {
        Page<Novel> page = new Page<>(current,pageSize);
        return novelMapper.selectVerifyingList(page);
    }

    @Override
    public String novelVerify(String novelId, VerifyState state) {
        if(state==null){
            throw new CustomException("不存在的状态");
        }
        Novel novel = new Novel();
        novel.setId(novelId);
        novel.setVerifyState(state.getValue());
        if (novelMapper.updateVerify(novelId,state.getValue())<=0){
            throw new CustomException("审核失败");
        }
        return novelId;
    }

    @Override
    public Integer updateSubscribe(String subscribeId, int number) {
        return novelMapper.updateSubscribe(subscribeId, number);
    }

    @Override
    public List<Novel> getRecentlyUpdate(Integer current, Integer pageSize) {
        Page<Novel> page = new Page<>(current,pageSize);
        return novelMapper.getRecentlyUpdate(page);
    }

    @Override
    public IPage<Novel> getAllRecommend(Integer current, Integer pageSize) {
        LambdaQueryWrapper<Novel> wrapper = new LambdaQueryWrapper<Novel>().eq(Novel::getRecommend, 1);
        // 分页
        Page<Novel> page = new Page<>(current, pageSize);
        return novelMapper.selectPage(page, wrapper);
    }

    @Override
    public IPage<Novel> rank(Integer current, Integer pageSize, SFunction<Novel, Integer> getter) {
        LambdaQueryWrapper<Novel> wrapper = new LambdaQueryWrapper<Novel>().eq(Novel::getVerifyState,1).orderByDesc(getter);
        return novelMapper.selectPage(new Page<>(current, pageSize), wrapper);
    }

    @Override
    public List<Novel> getPersonalComics(String username) {
        User user = userService.findUserByUsername(username);
        return list(new LambdaQueryWrapper<Novel>().eq(Novel::getAuthorId, user.getId()));
    }

    @Override
    public IPage<Novel> searchByName(Integer current, Integer pageSize, String novelName) {
        // 建立查询wrapper
        LambdaQueryWrapper<Novel> wrapper = new LambdaQueryWrapper<Novel>()
                .like(Novel::getNovelName, novelName)
                .eq(Novel::getVerifyState,VerifyState.VERIFIED.getValue());

        // 分页
        Page<Novel> page = new Page<>(current, pageSize);
        return novelMapper.selectPage(page, wrapper);
    }


    @Override
    public Integer updateCollectNum(String comicId, Integer value) {
        return novelMapper.updateCollectNum(comicId,value);
    }

    @Override
    public Integer updateCommentNum(String comicId, Integer value) {
        return novelMapper.updateCommentNum(comicId,value);
    }

    @Override
    public Integer updateState(String novelId, StateEnum state) {

        if (state==null){
            throw new CustomException("不存在的状态");
        }

        Novel novel = getById(novelId);
        if (novel==null){
            throw new CustomException("小说不存在");
        }
        User user = userService.getById(novel.getAuthorId());
        if (!user.getUsername().equals(UserRequestUtil.getCurrentUserName())){
            throw new CustomException("非用户本人不能修改状态");
        }
        return novelMapper.updateState(novelId,state.getValue());
    }

    @Override
    public IPage<Novel> getByState(Integer current, Integer pageSize, StateEnum state) {
        LambdaQueryWrapper<Novel> wrapper = new LambdaQueryWrapper<Novel>().eq(Novel::getState, state.getValue());
        return novelMapper.selectPage(new Page<>(current, pageSize), wrapper);
    }

}
